package com.ddxz.tools.license.common;

import com.ddxz.tool.core.convert.DateUtil;
import com.ddxz.tool.core.convert.StringUtil;
import com.ddxz.tool.core.security.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;

import static com.ddxz.tools.license.LicenseError.INVALID_LICENSE;
import static com.ddxz.tools.license.LicenseError.LICENSE_FILE_NOT_EXISTS;

/**
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/6/8
 */
public class LicenseCheck {
    public static boolean checkLicense() {
        return validLicense && (expiredTime > DateUtil.getTimestamp().longValue());
    }

    public static boolean installLicense(String fileName, String companyName, String applicationName) {
        File file = new File(fileName);
        if (!file.exists()) {
            logger.error(LICENSE_FILE_NOT_EXISTS.getMessage(), fileName);
            throw new DdxzLicenseException(LICENSE_FILE_NOT_EXISTS, fileName);
        }

        try(BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line = reader.readLine();
            List<String> parts = StringUtil.getList(SecurityUtil.rsaDecode(line), "\\.");
            validLicense = StringUtil.getList(parts.get(1)).contains(applicationName.toUpperCase())
                    && companyName.equals(parts.get(0));
            expiredTime = StringUtil.toLong(parts.get(2));
        } catch (Exception e) {
            logger.error("license ", e);
            throw new DdxzLicenseException(INVALID_LICENSE, e);
        }

        return true;
    }

    private static Boolean validLicense = false;

    private static long expiredTime;

    private static final Logger logger = LoggerFactory.getLogger(LicenseCheck.class);
}
